<template>
  <div>
    <el-page-header title="返回" content="创建装备" @back="$router.back()">
    </el-page-header>
    <div class="card">
      <div class="page-header">
        <h2>创建新装备</h2>
        <p class="page-desc">在这里创建你的专属装备，让游戏世界更加丰富多彩</p>
      </div>

      <el-form
        ref="formRef"
        label-position="top"
        :model="form"
        :rules="rules"
        label-width="70px"
      >
        <el-form-item prop="icon">
          <UploadImg
            tips="上传装备图标"
            :imgUrl="form.icon"
            width="100"
            height="100"
            @image-updated="handleIconUpdate"
          />
        </el-form-item>

        <el-form-item label="装备名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入装备名称，如：魔法长剑、守护之盾"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="装备描述" prop="desc">
          <el-input
            v-model="form.desc"
            :rows="3"
            type="textarea"
            placeholder="请详细描述装备的特性和效果"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="装备类型" prop="type">
          <div class="type-selector">
            <el-select
              v-model="form.sys"
              placeholder="选择系统"
              @change="handleSysChange"
              clearable
            >
              <el-option
                v-for="sys in uniqueSystems"
                :key="sys"
                :label="sys"
                :value="sys"
              />
            </el-select>

            <el-select
              v-model="form.type"
              placeholder="选择类型"
              @change="handleTypeChange"
              :disabled="!form.sys"
              clearable
            >
              <el-option
                v-for="type in availableTypes"
                :key="type"
                :label="type"
                :value="type"
              />
            </el-select>

            <el-select
              v-model="form.job"
              placeholder="选择职业"
              @change="handleJobChange"
              :disabled="!form.type"
              clearable
            >
              <el-option
                v-for="job in availableJobs"
                :key="job"
                :label="job"
                :value="job"
              />
            </el-select>

            <el-select
              v-model="form.solt"
              placeholder="选择装备位置"
              :disabled="!form.job"
              clearable
            >
              <el-option
                v-for="solt in availableSolts"
                :key="solt"
                :label="solt"
                :value="solt"
              />
            </el-select>
          </div>
        </el-form-item>

        <el-form-item label="装备来源" prop="source">
          <el-input
            v-model="form.source"
            placeholder="装备出处如小说，游戏，影视"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <div class="form-actions">
            <el-button @click="$router.back()" :disabled="submitting">取消</el-button>
            <el-button type="primary" @click="submitForm" :loading="submitting">
              {{ submitting ? "生成中..." : "好啦!" }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElNotification,
} from "element-plus";
import { HandDrawnNotification } from "@/tool/handDrawnToast";
import UploadImg from "@/components/UploadImg.vue";
import { callApi } from "@/tool/server";
import { useStore } from "vuex";

@Options({
  components: {
    UploadImg,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElButton,
  },
})
export default class CreateEquip extends Vue {
  private store = useStore();
  private submitting = false;

  // 表单数据
  form = {
    icon: "",
    name: "",
    desc: "",
    sys: "",
    type: "",
    job: "",
    solt: "",
    source: "",
  };

  // 表单验证规则
  rules = {
    icon: [{ required: true, message: "请上传装备图标", trigger: "change" }],
    name: [
      { required: true, message: "请输入装备名称", trigger: "blur" },
      { min: 1, max: 20, message: "装备名称长度在1到20个字符", trigger: "blur" },
    ],
    desc: [
      { required: true, message: "请输入装备描述", trigger: "blur" },
      { min: 1, max: 200, message: "装备描述长度在1到200个字符", trigger: "blur" },
    ],
    sys: [{ required: true, message: "体系选择", trigger: "change" }],
    type: [{ required: true, message: "类型选择", trigger: "change" }],
    job: [{ required: true, message: "种族选择", trigger: "change" }],
    solt: [{ required: true, message: "装备位置", trigger: "change" }],
    source: [
      { required: true, message: "请输入装备来源", trigger: "blur" },
      { min: 1, max: 50, message: "装备来源长度在1到50个字符", trigger: "blur" },
    ],
  };

  // 计算属性：获取唯一的系统列表
  get uniqueSystems() {
    const systems = [
      ...new Set(this.store.getters.equipTypes.map((item: any) => item.sys)),
    ];
    return systems.filter(Boolean);
  }

  // 计算属性：根据选择的系统获取可用的类型
  get availableTypes() {
    if (!this.form.sys) return [];
    const types = [
      ...new Set(
        this.store.getters.equipTypes
          .filter((item: any) => item.sys === this.form.sys)
          .map((item: any) => item.type)
      ),
    ];
    return types.filter(Boolean);
  }

  // 计算属性：根据选择的类型获取可用的职业
  get availableJobs() {
    if (!this.form.type) return [];
    const jobs = [
      ...new Set(
        this.store.getters.equipTypes
          .filter(
            (item: any) => item.sys === this.form.sys && item.type === this.form.type
          )
          .map((item: any) => item.job)
      ),
    ];
    return jobs.filter(Boolean);
  }

  // 计算属性：根据选择的职业获取可用的装备位置
  get availableSolts() {
    if (!this.form.job) return [];
    const solts = [
      ...new Set(
        this.store.getters.equipTypes
          .filter(
            (item: any) =>
              item.sys === this.form.sys &&
              item.type === this.form.type &&
              item.job === this.form.job
          )
          .map((item: any) => item.solt)
      ),
    ];
    return solts.filter(Boolean);
  }

  async mounted() {
    // 如果store中没有装备类型数据，则加载
    if (!this.store.getters.equipTypesLoaded) {
      await this.store.dispatch("loadEquipTypes");
    }
  }

  // 处理系统选择变化
  handleSysChange() {
    this.form.type = "";
    this.form.job = "";
    this.form.solt = "";
  }

  // 处理类型选择变化
  handleTypeChange() {
    this.form.job = "";
    this.form.solt = "";
  }

  // 处理职业选择变化
  handleJobChange() {
    this.form.solt = "";
  }

  // 处理图标上传
  handleIconUpdate(imgUrl: string) {
    this.form.icon = imgUrl;
  }

  // 提交表单
  async submitForm() {
    const formRef = this.$refs.formRef as any;
    if (!formRef) return;

    try {
      await formRef.validate();

      this.submitting = true;

      const result = await callApi("mod/CreateEquip", {
        icon: this.form.icon,
        name: this.form.name,
        desc: this.form.desc,
        source: this.form.source,
        sys: this.form.sys,
        type: this.form.type,
        job: this.form.job,
        solt_type: this.form.solt,
      });

      if (result) {
        HandDrawnNotification.success({
          title: "创建成功",
          message: `装备\"${this.form.name}\"创建成功！装备ID: ${
            result.equipId || "未知"
          }`,
          duration: 5000,
        });

        // 创建成功后自动返回
        this.$router.push("/");
      }
    } catch (error) {
      console.error("创建装备失败:", error);
      HandDrawnNotification.error({
        title: "创建失败",
        message: "创建装备失败，请检查表单信息后重试",
        duration: 5000,
      });
    } finally {
      this.submitting = false;
    }
  }

  // 重置表单
  resetForm() {
    const formRef = this.$refs.formRef as any;
    if (formRef) {
      formRef.resetFields();
    }
    this.form = {
      icon: "",
      name: "",
      desc: "",
      sys: "",
      type: "",
      job: "",
      solt: "",
      source: "",
    };
  }
}
</script>

<style scoped>
.card {
  max-width: 800px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.page-header {
  text-align: center;
}

.page-header h2 {
  color: #303133;
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-desc {
  color: #606266;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
}

.type-selector {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.type-selector .el-select {
  flex: 1;
  min-width: 120px;
}

.quality-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.range-separator {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  /* margin-top: 40px; */
  /* padding-top: 20px; */
}
:deep(.avatar-uploader) {
  padding: 0px;
}
:deep(.el-form-item__content) {
  justify-content: center;
}
/* :deep(.el-form-item) {
  margin-bottom: 0px;
} */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  transition: all 0.3s;
}

:deep(.el-textarea__inner:hover) {
  border-color: #409eff;
}

:deep(.el-select .el-input__inner),
:deep(.el-select .el-input__wrapper),
:deep(.el-select .el-input__inner input) {
  color: #303133 !important;
}

:deep(.el-select-dropdown__item.selected) {
  color: #ffe066 !important;
  font-weight: bold;
  background: rgba(255, 224, 102, 0.08);
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border: none;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.1);
}

:deep(.el-form-item.is-success .el-input__wrapper) {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.1);
}
</style>
